//
//  CTRefreshTableView.swift
//  CodingTest
//
//  Created by LYPC on 2021/11/18.
//

import UIKit

open class CTRefreshTableView: CTTableView {
    public private(set) weak var vm: CTTableViewRefreshProtocol?
}

public extension CTRefreshTableView {
    
    func setRefreshVM(_ vm: CTTableViewRefreshProtocol) {
        self.vm = vm
        vm.refreshTableView = self
    }
    func addHeaderFooterRefresh(noreMoreTips: NSAttributedString) {
        guard let vm = vm else { return }
        addRefreshHeader {  vm.refreshList() }
        addRefreshFooterV(noreMoreTips) {  vm.loadMoreList() }
    }
    func addHeader() {
        guard let vm = vm else { return }
        addRefreshHeader {  vm.refreshList() }
    }
    func addHeader(withBgColor color: UIColor, indicatorTint: UIColor? = nil) {
        guard let vm = vm else { return }
        addRefreshHeader(withBackgroundColor: color,
                                 indicatorTint: indicatorTint) {
                                 vm.refreshList()
        }
    }
    func addFooter(noreMoreTips: NSAttributedString) {
        guard let vm = vm else { return }
        addRefreshFooter(noreMoreTips) {  vm.loadMoreList() }
    }
    
    func addEmpty(attrTip: NSAttributedString,
                  type: ScrollViewErrorType = .empty,
                  topY: CGFloat = 0,
                  offsetY: CGFloat? = nil,
                  callback: (() -> Void)? = nil) {
        self.setEmpty(type: type,
                         tips: attrTip)
        { [weak self]() in
            self?.hideEmpty()
            self?.vm?.start2LoadData()
            callback?()
        }
        if let offsetY = offsetY
        { self.placeEmpty(topY: topY, offsetY: offsetY) }
    }
    
    func addError(tips: NSAttributedString,
                  topY: CGFloat = 0,
                  offsetY: CGFloat? = nil,
                  callback: (() -> Void)? = nil) {
    
        self.setError(tips: tips) { [weak self]() in
            self?.hideError()
            self?.vm?.start2LoadData()
            callback?()
        }
        if let offsetY = offsetY
        { self.placeError(topY: topY, offsetY: offsetY)}
    }
}
